﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using IGolovkine.Core.Diagnostics;

namespace IGolovkine.ShoutCastRipper.Filters
{
    public enum ContentTitleRegexFilterType
    {
        Accept,
        Reject
    }
    public class ContentTitleRegexFilterDefintion
    {
        private readonly Regex _regex;
        private readonly ContentTitleRegexFilterType _type;

        public ContentTitleRegexFilterDefintion(string regex, ContentTitleRegexFilterType type)
        {
            _regex = new Regex(regex, RegexOptions.Compiled | RegexOptions.IgnoreCase);
            _type = type;
        }

        public ContentTitleRegexFilterType Type
        {
            get { return _type; }
        }

        public string Pattern
        {
            get { return _regex.ToString(); }
        }

        public bool Matches(string title)
        {
            return _regex.IsMatch(title);
        }
    }

    public class ContentTitleRegexFilter : IContentTitleFilter
    {
        
        private readonly IEnumerable<ContentTitleRegexFilterDefintion> _filters;
        private readonly bool _acceptByDefault;
        public ContentTitleRegexFilter(IEnumerable<ContentTitleRegexFilterDefintion> patterns, bool acceptByDefault)
        {
            Debug.NotDefault(() => patterns);
            _filters = patterns;
            _acceptByDefault = acceptByDefault;
        }

        public string Name
        {
            get { return "Pattern Filter"; }
        }

        public ContentTitleFilterResult Process(string contentTitle)
        {
            foreach (ContentTitleRegexFilterDefintion filter in _filters)
            {
                if (filter.Matches(contentTitle))
                {
                    if (filter.Type == ContentTitleRegexFilterType.Accept)
                    {
                        return new ContentTitleFilterResult(string.Format("Accept '{0}'", filter.Pattern), true);
                    }
                    else
                    {
                        return new ContentTitleFilterResult(string.Format("Reject '{0}'", filter.Pattern), false);
                    }
                }
            }

            return new ContentTitleFilterResult(string.Format("'{0}' didn't match any of the filters, accepting", contentTitle), _acceptByDefault);
        }
    }
}
